<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '编辑'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="dataForm.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="deptName" label="所属部门">
        <ren-dept-tree v-model:model-value="dataForm.deptId" placeholder="选择部门" v-model:dept-name="dataForm.deptName"></ren-dept-tree>
      </el-form-item>
      <el-form-item prop="password" label="密码" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" label="确认密码" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item prop="realName" label="真实姓名">
        <el-input v-model="dataForm.realName" placeholder="真实姓名"></el-input>
      </el-form-item>
      <el-form-item prop="gender" label="性别">
        <ren-radio-group v-model:model-value="dataForm.gender" dict-type="gender"></ren-radio-group>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="手机号">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList" label="角色配置" class="role-list">
        <el-select v-model="dataForm.roleIdList" multiple placeholder="角色配置">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status" label="状态" size="small">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">停用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import debounce from 'lodash/debounce'
import {computed, nextTick, reactive, ref} from "vue";

import {isEmail, isMobile} from "../../../utils/validate.js";
import http from "../../../utils/request.js";
import {message} from "../../../utils/commonScript.js";

const emit = defineEmits(['refreshDataList'])

const dataFormRef = ref()
const visible = ref(false)
const roleList = ref([])
const roleIdListDefault = ref([])
let dataForm = reactive({
	id: '',
	username: '',
	deptId: '',
	deptName: '',
	password: '',
	confirmPassword: '',
	realName: '',
	gender: 0,
	email: '',
	mobile: '',
	roleIdList: [],
	status: 1
})
const dataRule = computed(() => {
	const validatePassword = (rule, value, callback) => {
		if (!dataForm.id && !/\S/.test(value)) {
			return callback(new Error('必填项不能为空'))
		}
		callback()
	};
	const validateConfirmPassword = (rule, value, callback) => {
		if (!dataForm.id && !/\S/.test(value)) {
			return callback(new Error('必填项不能为空'))
		}
		if (dataForm.password !== value) {
			return callback(new Error('确认密码与密码输入不一致'))
		}
		callback()
	};
	const validateEmail = (rule, value, callback) => {
		if (value && !isEmail(value)) {
			return callback(new Error('邮箱格式错误'))
		}
		callback()
	};
	const validateMobile = (rule, value, callback) => {
		if (value && !isMobile(value)) {
			return callback(new Error('手机号格式错误'))
		}
		callback()
	};
	return {
		username: [
			{ required: true, message: '必填项不能为空', trigger: 'blur' }
		],
		deptName: [
			{ required: true, message: '必填项不能为空', trigger: 'change' }
		],
		password: [
			{ validator: validatePassword, trigger: 'blur' }
		],
		confirmPassword: [
			{ validator: validateConfirmPassword, trigger: 'blur' }
		],
		realName: [
			{ required: true, message: '必填项不能为空', trigger: 'blur' }
		],
		email: [
			{ validator: validateEmail, trigger: 'blur' }
		],
		mobile: [
			{ validator: validateMobile, trigger: 'blur' }
		]
	}
})
const init = (id='') => {
	visible.value = true
	dataForm.deptId = ''
	dataForm.id = id
	nextTick(() => {
		dataFormRef.value.resetFields()
		roleIdListDefault.value = []
		Promise.all([
			getRoleList()
		]).then(() => {
			if (dataForm.id) {
				getInfo()
			}
		})
	})
}
// 获取角色列表
const getRoleList = () => {
	return http.get('/sys/role/list').then(({ data: res }) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}
		roleList.value = res.data
	}).catch(() => {})
}
// 获取信息
const getInfo = () => {
	http.get(`/sys/user/${dataForm.id}`).then(({ data: res }) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}

		dataForm.username = res.data.username
		dataForm.deptId = res.data.deptId
		dataForm.deptName = res.data.deptName
		dataForm.password = ''
		dataForm.confirmPassword =''
		dataForm.realName = res.data.realName
		dataForm.gender = res.data.gender
		dataForm.email = res.data.email
		dataForm.mobile = res.data.mobile
		dataForm.roleIdList = []
		dataForm.status = res.data.status

		// 角色配置, 区分是否为默认角色
		for (let i = 0; i < res.data.roleIdList.length; i++) {
			if (roleList.value.filter(item => item.id === res.data.roleIdList[i])[0]) {
				dataForm.roleIdList.push(res.data.roleIdList[i])
				continue
			}
			roleIdListDefault.value.push(res.data.roleIdList[i])
		}
	}).catch(() => {})
}
// 表单提交
const dataFormSubmitHandle = debounce(function () {
	dataFormRef.value.validate((valid) => {
		if (!valid) {
			return false
		}
		http[!dataForm.id ? 'post' : 'put']('/sys/user', {
			...dataForm,
			roleIdList: [
				...dataForm.roleIdList,
				...roleIdListDefault.value
			]
		}).then(({ data: res }) => {
			if (res.code !== 0) {
				return message.error(res.msg)
			}
			message({
				message: '操作成功',
				type: 'success',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		}).catch(() => {})
	})
}, 1000, { 'leading': true, 'trailing': false })
defineExpose({
	init
})
</script>

<style lang="scss">
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
